package com.example.productmanagerspringboot.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.productmanagerspringboot.data.entity.Good;
import com.example.productmanagerspringboot.data.vo.GoodsVO;
import com.example.productmanagerspringboot.mapper.GoodMapper;
import com.example.productmanagerspringboot.utils.UserRedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class GoodService {
    private final GoodMapper mapper;
    private final UserRedisUtils userRedisUtils;

    public GoodService(GoodMapper mapper, UserRedisUtils userRedisUtils) {
        this.mapper = mapper;
        this.userRedisUtils = userRedisUtils;
    }

    public GoodsVO getGoods(int pageNumber, int pageSize, boolean notSold) {
        Page<Good> page = new Page<>(pageNumber, pageSize);
        Page<Good> goodPage;
        if (notSold) {
            QueryWrapper<Good> wrapper = new QueryWrapper<>();
            wrapper.eq("sold", 0);
            goodPage = mapper.selectPage(page, wrapper);
        } else {
            goodPage = mapper.selectPage(page, null);
        }
        List<Good> records = goodPage.getRecords();
        return new GoodsVO(goodPage.getTotal(), pageNumber, records);
    }

    public Good getGoodById(int id) {
        return mapper.selectById(id);
    }

    public boolean addGood(Good good) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String name = authentication.getName();
        good.setOwnerId(userRedisUtils.getUserId());
        return mapper.insert(good) > 0;
    }

    public boolean editGood(Good good) {
        return mapper.updateById(good) > 0;
    }

    public boolean deleteGood(Good good) {
        return mapper.deleteById(good) > 0;
    }
}
